package org.ym.file.domain.model.node.common.download;

import org.apache.commons.io.FileUtils;
import org.ym.tools.FileTool;
import org.ym.tools.StreamTool;
import org.ym.tools.ZipTool;

import java.io.InputStream;
import java.nio.file.Path;

public class EncryptUpload implements UploadInterface{
    private static EncryptUpload instance;

    /**
     * 获取实例
     * @return
     */
    public static EncryptUpload getInstance(){
        if(instance == null){
            synchronized (EncryptUpload.class){
                if(instance == null){
                    instance = new EncryptUpload();
                }
            }
        }
        return instance;
    }
    @Override
    public FileUploadResult upload(InputStream source, FileUploadCommand fileUploadCommand) {
        Path filePath = null;
        try(InputStream inputStream = source){
            filePath = fileUploadCommand.getFilePath();
            long size = StreamTool.writeFile(inputStream, filePath);
            filePath = ZipTool.zip(fileUploadCommand.getFilePath(), fileUploadCommand.getPassword(), fileUploadCommand.getNewSuffix(), true);
            return FileUploadResult.builder().size(size).filePath(filePath).build();
        }catch (Exception e){
            //报错删除文件,防止文件冗余产生
            FileTool.deleteFile(filePath);
            throw new RuntimeException(e);
        }
    }

    @Override
    public FileUploadResult deal(FileUploadCommand fileUploadCommand) {
        Path filePath = null;
        try {
            long size = FileUtils.sizeOf(fileUploadCommand.getFilePath().toFile());
            filePath = ZipTool.zip(fileUploadCommand.getFilePath(), fileUploadCommand.getPassword(), fileUploadCommand.getNewSuffix(), true);
            return FileUploadResult.builder().filePath(filePath).size(size).build();
        }catch (Exception e){
            //报错删除文件,防止文件冗余产生
            FileTool.deleteFile(filePath);
            throw new RuntimeException(e);
        }
    }
}
